package dd.prog2.musterExercises.ws12set07_tanks;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

/**
 * Represents a tank which contains other tanks. Volume and surface
 * of the tank are defined by the sum of the corresponding properties
 * of all its parts.
 * @author Ruediger Lunde
 *
 */
public class CompositeTank implements Tank {
	private List<Tank> parts = new ArrayList<Tank>();

	/** Adds another part to the tank. */
	public void add(Tank part) {
		parts.add(part);
	}

	@Override
	public double getSurface() {
		double result = 0;
		for (Tank tank : parts)
			result += tank.getSurface();
		return result;
	}

	@Override
	public double getVolume() {
		double result = 0;
		for (Tank tank : parts)
			result += tank.getVolume();
		return result;
	}

	@Override
	public Iterator<Tank> iterator() {
		return parts.iterator();
	}

	/** Returns a deep copy. */
	@Override
	public CompositeTank clone() {
		CompositeTank result = null;
		try {
			result = (CompositeTank) super.clone();
		} catch (CloneNotSupportedException e) {
			// will never happen because Tank extends Cloneable
			e.printStackTrace();
		}
		result.parts = new ArrayList<Tank>(parts.size());
		for (Tank part : parts)
			result.parts.add(part.clone());
		return result;
	}
	
	public String toString() {
		NumberFormat nf = NumberFormat.getInstance(Locale.US);
		nf.setMaximumFractionDigits(1);
		return "CompositeTank(surface=" + nf.format(getSurface()) + ", volume="
				+ nf.format(getVolume()) + ")";
	}
}
